import { BadRequestException, Injectable } from '@nestjs/common'
import { RegisterDto } from './dto/registerDto'
import { LoginDto } from './dto/loginDto'
import { PrismaService } from 'src/common/prisma/prisma.service'
import * as bcrypt from 'bcryptjs'
import { JwtService } from 'src/jwt/jwt.service'

@Injectable()
export class AuthService {
   constructor(private readonly prisma: PrismaService, private jwtService: JwtService) {}

   async register(registerDto: RegisterDto) {
      const res = await this.prisma.user.create({
         data: {
            username: registerDto.username,
            password: bcrypt.hashSync(registerDto.password, 10)
         }
      })

      if (res.username) return { message: '注册成功' }
      throw new BadRequestException('出错了')
   }

   async login(loginDto: LoginDto) {
      const res = await this.prisma.user.findFirst({
         where: {
            username: loginDto.username
         }
      })

      if (bcrypt.compareSync(loginDto.password, res.password)) return this.jwtService.getToken(res.id + '')
      throw new BadRequestException('密码错误')
   }
}
